//
//  MKWebViewController.m
//  YangDongXi
//
//  Created by cocoa on 15/5/8.
//  Copyright (c) 2015年 yangdongxi. All rights reserved.
//

#import "MKWebViewController.h"
#import "AppDelegate.h"
#import <MJRefresh.h>
#import "MKUrlGuide.h"
#import <PureLayout.h>
#import "MBProgressHUD+MKExtension.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>

@interface MKWebViewController () <WKNavigationDelegate,WKUIDelegate>

@property (nonatomic, strong) NSString *urlString;

@property (nonatomic, strong) NSString *sttUrl;

/**
 *  建议在ios8以后使用wkwebview
 */
@property (nonatomic, strong) UIWebView *webView;

@property (strong, nonatomic) WKWebView *webView8;


@property (nonatomic, assign) BOOL isFirst;

@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;

@property (nonatomic, strong) NSLayoutConstraint *webViewTopConstraint;

@property (nonatomic, strong) UIView *customTopView;

@property (nonatomic, strong) NSString *blankHTML;

@property (nonatomic,strong) NSMutableArray * urlArray;

@property (nonatomic,strong)MBProgressHUD *hud;



@end


@implementation MKWebViewController

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"disablePullRefresh"];
    if (iOS8_OR_LATER) {
        
    } else {
        [self.webView.scrollView removeHeader];
        [self.webView.scrollView.header endRefreshing];
        [self.webView.scrollView removeHeader];
        self.webView.delegate = nil;
        [self.webView stopLoading];
    }
}

- (void)viewDidLoad
{
    
    self.isFirst = true;
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _urlArray = [NSMutableArray array];
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithHex:CardColorT]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{
                                                                      NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.blankHTML = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"blank" ofType:@"html"] encoding:NSUTF8StringEncoding error:NULL];
    if (iOS8_OR_LATER) {
        WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
        configuration.preferences = [WKPreferences new];
        configuration.preferences.javaScriptCanOpenWindowsAutomatically = false;
        
        
        self.webView8 = [[WKWebView alloc] init];
        [self.webView8 loadHTMLString:@"" baseURL:nil];
        self.webView8.navigationDelegate = self;
        self.webView8.UIDelegate = self;
        [self.view addSubview:self.webView8];
        [self.webView8 autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeTop];
        self.webViewTopConstraint = [self.webView8 autoPinEdgeToSuperviewEdge:ALEdgeTop];
    } else {
        self.webView = [[UIWebView alloc] init];
        [self.webView loadHTMLString:self.blankHTML baseURL:nil];
        self.webView.delegate = self;
        self.webView.scalesPageToFit = NO;
        [self.view addSubview:self.webView];
        [self.webView autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeTop];
        self.webViewTopConstraint = [self.webView autoPinEdgeToSuperviewEdge:ALEdgeTop];
    }
    
    
    self.activityIndicator = [[UIActivityIndicatorView alloc] init];
    self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.view addSubview:self.activityIndicator];
    [self.activityIndicator autoCenterInSuperview];
    
    if (self.urlString != nil)
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
                       {
                           if (iOS8_OR_LATER) {
                               [self.webView8 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
                           } else {
                               [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
                           }
                       });
    }
    
    [self updatePullRefreshStatus];
    [self addObserver:self forKeyPath:@"disablePullRefresh" options:NSKeyValueObservingOptionNew context:NULL];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"arrow_back_toward_gray20x23"]
                                                                             style:UIBarButtonItemStylePlain target:self
                                                                            action:@selector(backButtonClick)];
}

- (void)backButtonClick
{
    if (iOS8_OR_LATER) {
        if ([self.webView8 canGoBack]) {
            [self.webView8 goBack];
            return;
        }
    } else {
        if ([self.webView canGoBack])
        {
            [self.webView goBack];
            return;
        }
    }
//    if (_urlArray.count)
//        [_urlArray removeLastObject];
    if (self.navigationController.viewControllers[0] == self && self.presentingViewController != nil)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"disablePullRefresh"])
    {
        [self updatePullRefreshStatus];
    }
}

- (void)loadUrls:(NSString *)urlString
{
//    这边
    self.urlString = urlString;
    if (iOS8_OR_LATER) {
        if (self.webView8) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
                           {
                               [self.webView8 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
                           });
        }
    } else {
        if (self.webView != nil)
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
                           {
                               [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
                           });
        }
    }
}

- (void)customTopView:(UIView *)view
{
    [self.view removeConstraint:self.webViewTopConstraint];
    self.webViewTopConstraint = nil;
    [self.customTopView removeFromSuperview];
    
    [self.view addSubview:view];
    [view autoPinEdgesToSuperviewEdgesWithInsets:UIEdgeInsetsZero excludingEdge:ALEdgeBottom];
    if (iOS8_OR_LATER)
        [view autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.webView8];
    else
        [view autoPinEdge:ALEdgeBottom toEdge:ALEdgeTop ofView:self.webView];
    self.customTopView = view;
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (iOS8_OR_LATER)
        self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, getMainTabBar.tabBar.frame.size.height, 0);
    else
        self.webView8.scrollView.contentInset = UIEdgeInsetsMake(0, 0, getMainTabBar.tabBar.frame.size.height, 0);
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.isFirst) {
        self.isFirst = false;
    }else{
        if (self.urlArray.count) {
            //由h5到h5再到原生，回来之后保证页面显示正常
            if (iOS8_OR_LATER)
//                [self.webView8 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_urlArray[_urlArray.count - 2]]]];
                return;
            else
                [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_urlArray[_urlArray.count - 2]]]];
        }else{
            if (iOS8_OR_LATER)
//                [self.webView8 loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
                return;
            else
                [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
        }
        
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    if (iOS8_OR_LATER) {
        [self.webView8.scrollView.header endRefreshing];
//        self.webView8.hidden = YES;
    }
    else
        [self.webView.scrollView.header endRefreshing];
    [self.activityIndicator stopAnimating];
    self.activityIndicator.hidden = YES;
    
//    _hud.hidden = YES;
}

#pragma mark - wkwebview

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSString *urls = webView.URL.absoluteString;
//    self.sttUrl = urls;
//    [_urlArray addObject:self.sttUrl];
//    MyLog(@"%@",webView.URL.absoluteString);
    BOOL toGo = [[MKUrlGuide commonGuide] guideIgnoreWebVCForUrl:webView.URL.absoluteString];
    MyLog(@"toGo = %@",@(toGo));
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
//    MyLog(@"1");
//    NSString *urls = webView.URL.absoluteString;
//    self.sttUrl = urls;
//    [_urlArray addObject:self.sttUrl];
//    MyLog(@"%@",webView.URL.absoluteString);
//    BOOL toGo = [[MKUrlGuide commonGuide] guideIgnoreWebVCForUrl:webView.URL.absoluteString];
//    MyLog(@"toGo = %@",@(toGo));
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    webView.hidden = NO;
    NSString * js = [NSString stringWithFormat:@"$('.smart_menu,.foot,.member_header,.member_header_top,.member_box,.indextab,.indextab_box,.ps-head').hide();"];
    [self.webView8 evaluateJavaScript:js completionHandler:nil];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    MyLog(@"4");

}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//    NSString *urls = webView.URL.absoluteString;
//    self.sttUrl = urls;
//    if (_urlArray)
//        [_urlArray addObject:self.sttUrl];
//    MyLog(@"%@",webView.URL.absoluteString);
    if ([navigationAction.request.URL.absoluteString isEqualToString:@"about:blank"]) {
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    BOOL toGo = [[MKUrlGuide commonGuide] guideIgnoreWebVCForUrl:navigationAction.request.URL.absoluteString];
    if (toGo) {
        decisionHandler(WKNavigationActionPolicyCancel);
    } else
        decisionHandler(WKNavigationActionPolicyAllow);
    
}


#pragma mark - uiwebview
//js调用iOS
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    [self.activityIndicator startAnimating];
    self.activityIndicator.hidden = NO;

//    _hud = [MBProgressHUD showMessage:nil inView:self.webView wait:YES];


    NSString *urls = request.URL.absoluteString;
    self.sttUrl = urls;
    [_urlArray addObject:self.sttUrl];
    NSString * js = [NSString stringWithFormat:@"$('.smart_menu,.foot,.member_header,.member_header_top,.member_box,.indextab,.indextab_box,.ps-head').hide();"];
    [self.webView stringByEvaluatingJavaScriptFromString:js];
    
    WS(ws);
    JSContext *context = [_webView  valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"appGuideToHomePage"] = ^() {
        //返回首页点击方法
        [getMainTabBar guideToHomeViewController:ws];
    };
    
    JSContext * testContext = [_webView  valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    testContext[@"appBackToLastPage"] = ^() {
        //返回上一页点击方法
        [ws.navigationController popViewControllerAnimated:YES];
    };
    return ![[MKUrlGuide commonGuide] guideIgnoreWebVCForUrl:urls];
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [self.activityIndicator startAnimating];
    self.activityIndicator.hidden = NO;
//    _hud.hidden = NO;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self.webView.scrollView.header endRefreshing];
    [self.activityIndicator stopAnimating];
    self.activityIndicator.hidden = YES;
//    _hud.hidden = YES;
    
    if (self.title == nil)
    {
        self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    }
    
    NSString * js = [NSString stringWithFormat:@"$('.smart_menu,.foot,.member_header,.member_header_top,.member_box,.indextab,.indextab_box,.ps-head').hide();"];
    [self.webView stringByEvaluatingJavaScriptFromString:js];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//    [self.webView.scrollView.header endRefreshing];
//    [self.activityIndicator stopAnimating];
//    self.activityIndicator.hidden = YES;
    
    [_hud hide:YES];
    
    if ([error code] == NSURLErrorCancelled) return;
    NSArray * arr = [self.sttUrl componentsSeparatedByString:@"?"];
    NSString * urlString = arr[0];
    if (![urlString isEqualToString:@"http://www.ybaby.com/mobile/login.html"]) {
        [MBProgressHUD showMessage:@"加载失败了" wait:NO];
        [self.webView loadHTMLString:self.blankHTML baseURL:nil];
    }
    
}

- (void)webViewTitle:(NSString *)title
{
    self.title = title;
}

- (void)updatePullRefreshStatus
{
    if (self.disablePullRefresh)
    {
        if (iOS8_OR_LATER)
            [self.webView8.scrollView removeHeader];
        else
            [self.webView.scrollView removeHeader];
    }
    else
    {
        UIView *view;
        if (iOS8_OR_LATER) {
            view = self.webView8;
        } else {
            view = self.webView;
        }
        NSString *urlString = self.urlString;
        MJRefreshHeader *header = [self.webView.scrollView addLegendHeaderWithRefreshingBlock:^
                                   {
                                       if (iOS8_OR_LATER) {
                                           WKWebView *webView = (WKWebView *)view;
                                           if ([webView.URL.absoluteString isEqualToString:@"about:blank"])
                                           {
                                               [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
                                           }
                                           else
                                           {
                                               [webView reload];
                                           }
                                           
                                           
                                       } else {
                                           UIWebView *webView= (UIWebView *)view;
                                           if ([webView.request.URL.absoluteString isEqualToString:@"about:blank"])
                                           {
                                               [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]]];
                                           }
                                           else
                                           {
                                               [webView reload];
                                           }
                                       }
                                       
                                       
                                   }];
        header.updatedTimeHidden = YES;
    }
}

@end
